﻿using System.Text.RegularExpressions;
using System.Xml.Serialization;

namespace Altairis.OtpAuth.Core {
    [XmlRoot(ElementName = "otpVerifier", Namespace = XmlNs.SERIALIZATION_NS_URL)]
    public abstract class OtpVerifier {

        [XmlAttribute("secret")]
        public byte[] Secret { get; set; }

        [XmlAttribute("throttlingCount")]
        public int ThrottlingCount { get; set; }

        // Methods

        public abstract bool VerifyOneTimePassword(string otp);

        protected virtual bool VerifyPasswordSyntax(string otp, OtpGenerator generator) {
            if (string.IsNullOrWhiteSpace(otp)) return false;
            var maxLength = generator.Digits;
            if (generator.UseChecksumDigit) {
                if (otp.Length < 2) return false;
                var corectOtp = generator.AddChecksumDigit(otp.Substring(0, otp.Length - 1));
                if (otp.Equals(corectOtp)) return false;
                maxLength++;
            }
            var otpRegex = string.Format("^[0-9]{{{0}}}$", maxLength);
            return (Regex.IsMatch(otp, otpRegex));
        }

    }
}
